<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// cloud info
$username = "greengarinc"; // username
$key = "e7d31711dbfe01b9085117422201e58b"; // api key
// 
//// Connect to Rackspace
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);

// store file information
$localfile = $_FILES['userfile']['tmp_name'];
$md5 = md5_file($_FILES['userfile']['tmp_name']);
$filename = "$md5.png";

//// Get the container we want to use
//$container = $conn->get_container("drawings.$id.whiteboard.greengar.com");
$container = NULL;
$container_id = substr($md5, 0, 4);
if(!$container) {
    $container = $conn->create_container("games.$container_id.drawtogether.greengar.com");
    $container->make_public(86400 * 3);
}
if($container) {
    // upload file to Rackspace
    try {
        $object = $container->create_object($filename);
        $object->load_from_filename($localfile);
        $url = mysql_real_escape_string($container->cdn_uri . "/$md5.png");
        $cloudImage = imagecreatefrompng($localfile);
        $src_w = imagesx($cloudImage);
        $src_h = imagesy($cloudImage);
        $dst_w = $src_h / 16;
        $dst_h = $src_h / 16;
        $cloudThumnail = imagecreatetruecolor($dst_w, $dst_h);
        imagecopyresized($cloudThumnail, $cloudImage, 0, 0, $src_w, $src_h, 0, 0, $dst_w, $dst_h);
        if($cloudThumnail) {
            $localfile = dirname(__FILE__)."/temp_$md5.png";
            if(imagepng($cloudThumnail, $localfile)) {
                $filename = "thumb_$md5.png";
                $thumb_url = mysql_real_escape_string($container->cdn_uri . "/thumb_$md5.png");
                $object = $container->create_object($filename);
                $object->load_from_filename($localfile);
                unlink($localfile);

            }
        }

        imagedestroy($cloudImage);
        imagedestroy($cloudThumnail);
    } catch (Exception $e) {

    }
}

$user_id = get_loggedin_userid();
$noun_id = $user_id;

$adjective_id = get_input('adjective_id');
$noun = get_input('noun');
$noun_url = $url;
$noun_thumbnail_url = $thumb_url;
$prev_game_id = get_input('prev_game_id');
$turn = get_input('turn');

if(dt_create_game($noun_id, $adjective_id, $noun, $noun_url, $noun_thumbnail_url, $prev_game_id, $turn)) {
    echo json_encode(export_result(200, "1"));
} else {
    echo json_encode(export_result(400, "0"));
}

?>
